/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.jittojava.core.manager;

import com.inspur.edp.jittojava.context.JitContext;
import com.inspur.edp.jittojava.core.JitUtils;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackageHeader;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.entity.ProcessMode;
import com.inspur.edp.lcm.metadata.api.entity.ProjectHeader;
import com.inspur.edp.lcm.metadata.api.mvnEntity.MavenPackageRefs;
import com.inspur.edp.lcm.metadata.common.Utils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GeneratorManagerForInterpretation extends GeneratorManager {

    public GeneratorManagerForInterpretation() {
        archetypePath = JitUtils.getCompArchetypePath();
        archetypeTarget = JitUtils.getCompArchetypeTarget();
        archetypeArtifactId = JitUtils.getCompArchetypeArtifactId();
        refModule = "comp";
    }

    @Override
    public void generate(String absolutePath, String mavenPath) throws Exception {
        try {
            //构建生成上下文
            jitContext = buildJitContext(absolutePath);
            //创建maven工程与模块
            createMavenProject(jitContext, mavenPath);
            //生成后事件
            afterGenerate(absolutePath);
        } finally {
        }
    }

    @Override
    public void generateApi(String absolutePath, String mavenPath) {
    }

    @Override
    protected void beforeGenerate(String absolutePath) {
    }

    @Override
    protected void clearCode(String javaProjectPath) {
    }

    @Override
    protected void generateCode(JitContext jitContext) {
    }

    @Override
    protected List<MavenPackageRefs> getGenerationMavenPackageRefs(MetadataProject metadataProject, String mavenPath) {
        List<MavenPackageRefs> generationMavenPackageRefsWithVersion = new ArrayList<>();
        if (metadataProject.getMavenPackageRefs() != null && metadataProject.getMavenPackageRefs().size() > 0) {
            for (MavenPackageRefs mavenPackageRefs : metadataProject.getMavenPackageRefs()) {
                // 如果有bo内引用，可以根据bo内引用确定元数据包名
                if (metadataProject.getProjectRefs() != null && metadataProject.getProjectRefs().size() > 0) {
                    final String[] split = mavenPackageRefs.getArtifactId().split("-");
                    String projectName = split[2];
                    String projectNameOrElse = "bo-" + split[2];
                    final ProjectHeader projectHeader = metadataProject.getProjectRefs().stream().filter(ref -> ref.getProjectPath().endsWith(projectName) || ref.getProjectPath().endsWith(projectNameOrElse)).findFirst().orElse(null);
                    if (projectHeader != null) {
                        final MetadataPackageHeader metadataPackageHeader = metadataProject.getMetadataPackageRefs().stream().filter(ref -> ref.getName().equals(projectHeader.getName())).findFirst().orElse(null);
                        if (metadataPackageHeader != null) {
                            if (metadataPackageHeader.getProcessMode() == null || ProcessMode.GENERATION.equals(metadataPackageHeader.getProcessMode())) {
                                generationMavenPackageRefsWithVersion.add(mavenPackageRefs);
                            }
                            continue;
                        }
                    }
                }

                // 如果不是bo内引用，则去maven文件夹下去找元数据包名
                File mavenPackagePath = Paths.get(mavenPath).resolve(mavenPackageRefs.getGroupId() + "-" + mavenPackageRefs.getArtifactId() + "-" + mavenPackageRefs.getVersion()).toFile();
                // 如果不存在，先install
                if (!mavenPackagePath.exists()) {
                    try {
                        mdpkgService.installMdpkg(mavenPackageRefs.getGroupId(), mavenPackageRefs.getArtifactId(), mavenPackageRefs.getVersion(), jitContext.getGspProjectpath(), false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (!mavenPackagePath.exists()) {
                    continue;
                }
                final File mdpkgFile = Arrays.stream(mavenPackagePath.listFiles()).filter(file -> file.getName().endsWith(Utils.getMetadataPackageExtension())).findFirst().orElse(null);
                if (mdpkgFile != null) {
                    final MetadataPackageHeader metadataPackageHeader = metadataProject.getMetadataPackageRefs().stream().filter(header -> (header.getName() + Utils.getMetadataPackageExtension()).equals(mdpkgFile.getName())).findFirst().orElse(null);
                    if (metadataPackageHeader != null && (metadataPackageHeader.getProcessMode() == null || ProcessMode.GENERATION.equals(metadataPackageHeader.getProcessMode()))) {
                        generationMavenPackageRefsWithVersion.add(mavenPackageRefs);
                    }
                }
            }
        }
        return generationMavenPackageRefsWithVersion;
    }
}
